# -*- coding: utf-8 -*-
"""
Time    : 2024-4-16 10:56
ProjectName    : flask-pro-test
FileName    : views.py.py
"""

import os.path
import base64
from flask import session, jsonify, g, request
from flask_restx import Namespace, Resource, reqparse, fields
from werkzeug.utils import secure_filename
from config import BaseConfig

from utils.response_code import RET
from utils.common import login_required, allowed_file

from apps.models.gallery import Gallery

# from . import gallery_model

api = Namespace(name="gallery", description="图库列表")

# 定义文件模型，支持上传多个文件
gallery_model = api.parser()
gallery_model.add_argument('files', type=fields.List(fields.Raw(type='file')), location='files', required=True,
                           help='Multiple files')


# 上传文件
@api.route("/upload/file")
class UploadFile(Resource):
    @api.doc(description="上传文件功能")
    @api.expect(gallery_model)
    @login_required
    def post(self):
        files = request.files.getlist('files')
        for file in files:
            if file and allowed_file(file.filename):
                # 上传的文件名必须是非中文
                filename = secure_filename(file.filename)
                file.save(os.path.join(BaseConfig.UPLOAD_FOLDER) + filename)
                path_image = os.path.join(BaseConfig.UPLOAD_FOLDER) + filename
                with open(path_image, 'rb') as f:
                    image_data = base64.b64encode(f.read()).decode("utf-8")
                i_dict = {"name": filename, "image": image_data}
                gallery = Gallery(i_dict)
                gallery.save_data()
            else:
                api.logger.info("图片[ %s ]格式，不支持上传" % file.filename)
                return jsonify(
                    code=RET.IOERR,
                    message="图片[ %s ]格式，不支持上传" % file.filename,
                )
        return jsonify(
            code=RET.OK,
            message="上传文件成功",
        )


# 获取所有的图片

# 删除图片
# class DelGallery(Resource):
#     def delete(self):





